<template>
    <div class="agri-bg">
        <div class="agri-header">
            <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                <ellipse cx="30" cy="30" rx="28" ry="18" fill="#e8f5e9"/>
                <path d="M15 40 Q30 10 45 40" stroke="#67c23a" stroke-width="3" fill="none"/>
                <ellipse cx="30" cy="30" rx="6" ry="12" fill="#a5d6a7"/>
            </svg>
            <h2 class="register-title">
                创建新账号
                <svg class="leaf-icon" width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M2 20 Q12 2 20 10 Q10 18 2 20 Z" fill="#67c23a"/>
                </svg>
            </h2>
            <p class="register-subtitle">加入我们的农产品融销一体平台</p>
        </div>
        <div class="register-container">
            <el-form ref="registerForm" :model="registerForm" :rules="rules" class="register-form">
                <div class="form-content">
                    <el-form-item prop="username">
                        <el-input 
                            v-model="registerForm.username" 
                            placeholder="请输入用户名"
                            prefix-icon="el-icon-user">
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="password">
                        <el-input 
                            type="password" 
                            v-model="registerForm.password" 
                            placeholder="请设置密码"
                            prefix-icon="el-icon-lock">
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="name">
                        <el-input 
                            v-model="registerForm.name" 
                            placeholder="请输入真实姓名"
                            prefix-icon="el-icon-user">
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="email">
                        <el-input 
                            v-model="registerForm.email" 
                            placeholder="请输入邮箱"
                            prefix-icon="el-icon-message">
                        </el-input>
                    </el-form-item>

<!--                    <el-form-item prop="code">-->
<!--                        <div class="validate-container">-->
<!--                            <el-input -->
<!--                                v-model="registerForm.code" -->
<!--                                placeholder="请输入验证码"-->
<!--                                prefix-icon="el-icon-chat-line-round">-->
<!--                            </el-input>-->
<!--                            <el-button -->
<!--                                type="success" -->
<!--                                :disabled="disabled"-->
<!--                                class="validate-btn"-->
<!--                                @click="sendVerificationCode">-->
<!--                                {{ buttonContent }}-->
<!--                            </el-button>-->
<!--                        </div>-->
<!--                    </el-form-item>-->

                    <el-form-item prop="role">
                        <el-select 
                            v-model="registerForm.role" 
                            placeholder="请选择用户角色"
                            class="role-select">
                            <el-option label="普通用户" value="USER"></el-option>
                            <el-option label="农户" value="FARMER"></el-option>
                            <el-option label="管理员" value="ADMIN"></el-option>
                        </el-select>
                    </el-form-item>

<!--                    <el-form-item prop="invitationCode" v-if="registerForm.role === 'ADMIN'">-->
<!--                        <el-input -->
<!--                            v-model="registerForm.invitationCode" -->
<!--                            placeholder="请输入管理员邀请码"-->
<!--                            prefix-icon="el-icon-key">-->
<!--                            <template slot="append">-->
<!--                                <el-tooltip content="请联系超级管理员获取邀请码" placement="top">-->
<!--                                    <i class="el-icon-question"></i>-->
<!--                                </el-tooltip>-->
<!--                            </template>-->
<!--                        </el-input>-->
<!--                    </el-form-item>-->

                    <el-form-item>
                        <el-button 
                            type="success" 
                            class="register-button"
                            @click="onRegister">
                            立即注册
                        </el-button>
                    </el-form-item>

                    <div class="register-actions">
                        <el-link type="success" @click="$router.push('/login')">
                            <i class="el-icon-arrow-left"></i> 返回登录
                        </el-link>
                    </div>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import request from "@/utils/request";

export default {
    name: 'Register',
    data() {
        // 验证邀请码
        const validateInvitationCode = (rule, value, callback) => {
            if (this.registerForm.role === 'ADMIN') {
                if (!value) {
                    callback(new Error('请输入管理员邀请码'));
                } else if (value !== 'ADMIN666') { // 邀请码写死为ADMIN666
                    callback(new Error('邀请码不正确'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        return {
            countdown: 0,
            disabled: false,
            timer: null,
            emailCode: '',
            buttonContent: '发送验证码',
            registerForm: {
                username: '',
                password: '',
                name: '',
                email: '',
                code: '',
                role: 'USER',
                status: 1,
                invitationCode: '' // 添加邀请码字段
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入真实姓名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'blur' }
                ],
                role: [
                    { required: true, message: '请选择用户角色', trigger: 'change' }
                ],
                invitationCode: [
                    { validator: validateInvitationCode, trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        sendVerificationCode() {
            if (this.disabled) return;
            
            if (!this.registerForm.email) {
                this.$message.error('请先输入邮箱地址');
                return;
            }

            request.get(`/email/sendEmail/${this.registerForm.email}`).then(res => {
                if (res.code === '0') {
                    this.$message({
                        type: 'success',
                        message: "验证码已发送到您的邮箱,请查收"
                    });
                    console.log(res.data);
                    this.emailCode = res.data;
                    this.startCountdown();
                } else {
                    this.$message({
                        type: 'error',
                        message: res.msg
                    });
                }
            });
        },
        
        startCountdown() {
            this.countdown = 60;
            this.disabled = true;
            this.buttonContent = `${this.countdown}秒后重试`;

            this.timer = setInterval(() => {
                if (this.countdown > 0) {
                    this.countdown--;
                    this.buttonContent = `${this.countdown}秒后重试`;
                } else {
                    clearInterval(this.timer);
                    this.disabled = false;
                    this.buttonContent = '发送验证码';
                }
            }, 1000);
        },

        onRegister() {
            this.$refs.registerForm.validate((valid) => {
                if (valid) {
                    // 将验证码转换为字符串后再比较
                    // if (String(this.registerForm.code) !== String(this.emailCode)) {
                    //     console.log('Input code:', this.registerForm.code, 'Expected code:', this.emailCode);
                    //     this.$message({
                    //         type: 'error',
                    //         message: '验证码不正确'
                    //     });
                    //     return;
                    // }

                    // 如果是管理员注册，验证邀请码
                    // if (this.registerForm.role === 'ADMIN' &&
                    //     this.registerForm.invitationCode !== 'ADMIN666') {
                    //     this.$message({
                    //         type: 'error',
                    //         message: '管理员邀请码不正确'
                    //     });
                    //     return;
                    // }

                    request.post("/user/add", this.registerForm).then(res => {
                        if (res.code === '0') {
                            this.$message({
                                type: 'success',
                                message: "注册成功，请登录"
                            });
                            this.$router.push('/login');
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.msg
                            });
                        }
                    });
                }
            });
        }
    },
    beforeDestroy() {
        clearInterval(this.timer);
    }
};
</script>

<style scoped>
.agri-bg {
    min-height: 100vh;
    background: linear-gradient(135deg, #e8f5e9 0%, #fffde7 100%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.agri-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 18px;
}

.register-title {
    font-size: 32px;
    color: #388e3c;
    margin-bottom: 8px;
    text-align: center;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 8px;
}

.leaf-icon {
    vertical-align: middle;
}

.register-subtitle {
    font-size: 16px;
    color: #8d6e63;
    margin-bottom: 32px;
    text-align: center;
}

.register-container {
    width: 100%;
    max-width: 400px;
    background: #f9fbe7;
    border-radius: 22px;
    box-shadow: 0 6px 32px 0 rgba(103, 194, 58, 0.10), 0 1.5px 6px 0 #a1887f22;
    padding: 36px 32px 28px 32px;
    margin: 0 auto;
    animation: fadeIn 0.6s ease-out;
}

.register-form {
    margin-top: 0;
}

.form-content {
    width: 90%;
    margin: 0 auto;
}

.validate-container {
    display: flex;
    gap: 16px;
}

.validate-btn {
    flex-shrink: 0;
    width: 120px;
    border-radius: 8px;
    height: 44px;
    font-size: 15px;
    background: linear-gradient(90deg, #67c23a 0%, #43a047 100%);
    color: #fff;
    border: none;
    transition: all 0.3s ease;
}

.validate-btn:disabled {
    background: #c8e6c9;
    color: #fff;
}

.role-select {
    width: 100%;
}

.register-button {
    width: 100%;
    height: 44px;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 1px;
    margin-top: 20px;
    border-radius: 10px;
    background: linear-gradient(90deg, #67c23a 0%, #43a047 100%);
    color: #fff;
    border: none;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
}

.register-button:hover {
    background: linear-gradient(90deg, #43a047 0%, #67c23a 100%);
    transform: translateY(-2px) scale(1.03);
    box-shadow: 0 4px 16px rgba(103, 194, 58, 0.18);
}

.register-actions {
    display: flex;
    justify-content: center;
    margin-top: 24px;
    font-size: 14px;
}

.register-actions .el-link {
    display: flex;
    align-items: center;
    gap: 4px;
    color: #43a047;
}

.el-input-group__append {
    padding: 0 10px;
    cursor: help;
}

.el-input-group__append i {
    font-size: 16px;
    color: #909399;
}

.el-tooltip {
    cursor: help;
}

:deep(.el-input__inner) {
    height: 44px;
    line-height: 44px;
    border-radius: 10px;
    border: 1.5px solid #a5d6a7;
    background: #fff;
    transition: all 0.3s ease;
    font-size: 15px;
}

:deep(.el-input__inner:focus) {
    border-color: #67c23a;
    box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.13);
}

:deep(.el-form-item) {
    margin-bottom: 22px;
}

:deep(.el-input__prefix) {
    left: 12px;
    top: 0;
    height: 100%;
    display: flex;
    align-items: center;
}

:deep(.el-input__prefix i) {
    font-size: 16px;
    line-height: 1;
    display: flex;
    align-items: center;
}

:deep(.el-input__inner) {
    padding-left: 38px;
}

:deep(.el-select .el-input__inner) {
    padding-left: 15px;
}

:deep(.el-select .el-input__suffix) {
    display: flex;
    align-items: center;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@media (max-width: 480px) {
    .form-content {
        width: 100%;
    }
    .register-container {
        padding: 18px 6px 18px 6px;
    }
}
</style>